package wiki.xsx.core.jmeter.core.controller;

import wiki.xsx.core.jmeter.core.util.JmeterOptional;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.testelement.TestElement;

/**
 * 默认循环控制器
 *
 * @author xsx
 * @date 2022/8/22
 * @since 1.8
 * <p>
 * Copyright (c) 2022 xsx All Rights Reserved.
 * easy-jmeter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * </p>
 */
@Data
@Accessors(chain = true)
public class JmeterDefaultLoopController implements JmeterLoopController {

    /**
     * 循环名称
     */
    private String name;
    /**
     * 循环注释
     */
    private String comment;
    /**
     * 循环次数
     */
    private Integer loopNum;
    /**
     * 是否永远（不限次数）
     */
    private Boolean isContinueForever;

    /**
     * 无参构造
     */
    private JmeterDefaultLoopController() {
    }

    /**
     * 获取循环控制器实例
     *
     * @return 返回循环控制器实例
     */
    public static JmeterDefaultLoopController getInstance() {
        return new JmeterDefaultLoopController();
    }

    /**
     * 创建循环控制器
     *
     * @return 返回循环控制器
     */
    @Override
    public LoopController create() {
        // 创建循环控制器
        LoopController loopController = new LoopController();
        // 设置测试类名称
        loopController.setProperty(TestElement.TEST_CLASS, TEST_CLASS_NAME);
        // 设置GUI类名称
        loopController.setProperty(TestElement.GUI_CLASS, GUI_CLASS_NAME);
        // 设置启用
        loopController.setEnabled(true);
        // 设置循环名称
        loopController.setName(JmeterOptional.ofNullable(this.name).orElse("测试循环控制器"));
        // 设置循环注释
        loopController.setComment(JmeterOptional.ofNullable(this.comment).orElse(""));
        // 设置循环次数（默认：1）
        loopController.setLoops(JmeterOptional.ofNullable(this.loopNum).orElse(1));
        // 设置是否永远（不限次数）
        loopController.setContinueForever(JmeterOptional.ofNullable(this.isContinueForever).orElseGet(() -> loopController.getLoops() == -1));
        // 初始化循环控制器
        loopController.initialize();
        // 返回循环控制器
        return loopController;
    }
}
